package com.jessehu.dataquery.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.jessehu.dataquery.R;
import com.jessehu.dataquery.dbtable.Person;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 搜索结果适配器
 *
 * @author JesseHu
 * @date 2018/12/20
 */
public class QueryResultAdapter extends BaseAdapter {
    private List<Person> mPersonList;
    private LayoutInflater mInflater;

    public QueryResultAdapter(Context mContext, List<Person> mPersonList) {
        this.mPersonList = mPersonList;
        mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    /**
     * 数据量，view显示的条数，如果为0，则不显示
     *
     * @return
     */
    @Override
    public int getCount() {
        return mPersonList.size();
    }

    /**
     * 数据中索引值对应的数据
     *
     * @param position
     * @return
     */
    @Override
    public Object getItem(int position) {
        return mPersonList.get(position);
    }

    /**
     * 每一条数据对应的索引值，即ListView中每一行的索引
     *
     * @param position
     * @return
     */
    @Override
    public long getItemId(int position) {
        return position;
    }

    /**
     * 每一条数据所展示的视图，即ListView中每一行
     *
     * @param position
     * @param convertView
     * @param parent
     * @return
     */
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        StudentHolder studentHolder;
        if (null == convertView) {
            // 获取每个item视图
            convertView = mInflater.inflate(R.layout.item_student, parent, false);
            studentHolder = new StudentHolder(convertView);
            convertView.setTag(studentHolder);
        } else {
            studentHolder = (StudentHolder) convertView.getTag();
        }
        Person student = mPersonList.get(position);
        // 设置显示的数据
        studentHolder.nameTv.setText(student.getName());
        studentHolder.ageTv.setText(String.valueOf(student.getAge()));
        String sex = student.getSex() == 0 ? "女" : "男";
        studentHolder.sexTv.setText(sex);
        return convertView;
    }

    /**
     * 使用ViewHolder进行优化，减少item视图对象的重复创建
     */
    class StudentHolder {
        @BindView(R.id.tv_item_name)
        TextView nameTv;
        @BindView(R.id.tv_item_age)
        TextView ageTv;
        @BindView(R.id.tv_item_sex)
        TextView sexTv;

        StudentHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
